package com.zmt.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmt.content.dto.AddCourseDto;
import com.zmt.content.dto.CourseBaseInfoDto;
import com.zmt.content.dto.EditCourseDto;
import com.zmt.content.mapper.*;
import com.zmt.content.po.*;
import com.zmt.xuechengplusbase.exception.xuechengplusException;
import com.zmt.xuechengplusbase.model.PageParams;
import com.zmt.xuechengplusbase.model.PageResult;
import com.zmt.content.dto.QueryCourseParamsDto;
import com.zmt.content.service.CourseBaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class CourseBaseServiceImpl implements CourseBaseService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    @Autowired
    private TeachplanMapper teachplanMapper;

    /**
     * 分页查询
     * @param pageParams
     * @param queryCourseParamsDto
     * @return
     */
    @Override
    public PageResult queryCourseBaseList(Long companyId,PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        // TODO 判断参数是否合法

        //就当成一个分页查询来写。
        Page<CourseBase> pageInfo = new Page<>(pageParams.getPageNo(),pageParams.getPageSize());
        LambdaQueryWrapper<CourseBase> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
        wrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
        wrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus,queryCourseParamsDto.getPublishStatus());
        wrapper.eq(CourseBase::getCompanyId,companyId);
        Page<CourseBase> page = courseBaseMapper.selectPage(pageInfo, wrapper);
        List<CourseBase> records = page.getRecords();
        long total = page.getTotal();

        PageResult pageResult = new PageResult(records,total,pageParams);
        return pageResult;
    }


    /**
     * 添加课程
     * @param companyId
     * @param addCourseDto
     * @return
     */
    @Transactional//增删改的方法都要加上事务注解
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        //参数合法性校验  终于理解为什么即使Controller校验过了还是需要在这里校验。因为日后可能进行RPC调用，调用者就不是Controller了
        if (companyId==null){
            xuechengplusException.cast("机构id为空");
        }

        // 向CourseBase表中写入信息
        CourseBase courseBase = new CourseBase();
        //进行copy复制，addCourseDto中的数据与CourseBase的数据，只要字段对应的上都可以复制过去
        BeanUtils.copyProperties(addCourseDto,courseBase);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now());
        //设置审核状态默认为未审核
        courseBase.setAuditStatus("202002");
        //发布状态为未发布
        courseBase.setStatus("203001");

        int success = courseBaseMapper.insert(courseBase);
        if (success==0){
            throw new RuntimeException("课程添加信息失败");
        }
        if (success==1){
            //说明欧克
        }
        // 向CourseMarket写入数据
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto,courseMarket);
        //courseMarket的主键就是CourseBase的主键
        Long id = courseBase.getId();

        courseMarket.setId(id);
        int result = updateCourseMarket(courseMarket);
        if (result==0){
            //说明插入或更改失败
            throw new RuntimeException("信息保存失败");
        }
        //保存完后，需要查找信息
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(id);
        return courseBaseInfo;
    }

    /**
     * 查询保存后的信息返回给前端展示
     * 查询课程信息进行回显
     *
     * TODO 这里加一条不是本机构的课程，那就不能看（老六项目）
     * @param id
     * @return
     */
    public CourseBaseInfoDto getCourseBaseInfo(Long id){

        //  有bug，如果保存的信息有一张表查不出来就啥也显示不出来(已解决)

        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        //查找两张表
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if (courseBase!=null){
            BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        if (courseMarket!=null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }
        //进行组装

        //大小标签的名字我们也要知道然后组装起来
        /**
         * 应该还有更简单的方法
         */
        String mt = courseBase.getMt();
        String st = courseBase.getSt();

        CourseCategory courseCategoryM = courseCategoryMapper.selectById(mt);
        String nameM = courseCategoryM.getName();
        CourseCategory courseCategoryS = courseCategoryMapper.selectById(st);
        String nameS = courseCategoryS.getName();

        courseBaseInfoDto.setMtName(nameM);
        courseBaseInfoDto.setStName(nameS);

        /**
         * 有没有第二种实现方法？？
         */
        return courseBaseInfoDto;
    }

    @Override
    @Transactional
    public CourseBaseInfoDto updateCourse(Long companyId,EditCourseDto editCourseDto) {
        /**
         * 笑死了，所有机构用的都是一个系统，互相看老底是吧？
         * 之后把TODO之前的内容换到getCourseBaseInfo中
         */
        Long id = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if (courseBase==null) {
            //逻辑乱死了，都进行回显了，哪能不存在吗？
            xuechengplusException.cast("课程不存在");
        }
        Long companyId1 = courseBase.getCompanyId();
        if (!companyId.equals(companyId1)){
            xuechengplusException.cast("只能修改本机构的课程");
        }

        BeanUtils.copyProperties(editCourseDto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        int upCourse = courseBaseMapper.updateById(courseBase);
        if (upCourse<=0){
            xuechengplusException.cast("修改课程信息表失败");
        }
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        int upCourseMarket = updateCourseMarket(courseMarket);
        if (upCourseMarket<=0){
            xuechengplusException.cast("修改课程营销表失败");
        }

        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(id);
        return courseBaseInfo;
    }

    @Override
    @Transactional
    public void deleteCourse(Long courseId) {
        /**
         * 分析一波。删除一套课程需要删除教师表中相关内容，媒资中的内容，营销中的内容，
         * 似乎可以根据courseId删除所有表
         */
        //删除教师信息
        LambdaQueryWrapper<CourseTeacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseTeacher::getCourseId,courseId);
        if (courseTeacherMapper.delete(wrapper)<0){
            xuechengplusException.cast("删除教师信息失败");
        }
        //删除课程计划信息
        LambdaQueryWrapper<Teachplan> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Teachplan::getCourseId,courseId);
        if (teachplanMapper.delete(wrapper1)<0){
            xuechengplusException.cast("删除课程计划信息失败");
        }
        //删除课程媒资信息
        LambdaQueryWrapper<TeachplanMedia> wrapper2 = new LambdaQueryWrapper<>();
        if (teachplanMediaMapper.delete(wrapper2)<0){
            xuechengplusException.cast("删除媒资信息失败");
        }
        //删除课程营销信息
        LambdaQueryWrapper<CourseMarket> wrapper3 = new LambdaQueryWrapper<>();
        if (courseMarketMapper.delete(wrapper3)<0){
            xuechengplusException.cast("删除课程营销失败");
        }
        //删除课程基本信息
        if (courseBaseMapper.deleteById(courseId)<=0){
            xuechengplusException.cast("删除课程失败");
        }

    }


    /**
     * update营销信息，存在则更新，不存在则插入
     * @param courseMarket
     * @return
     */
    private int updateCourseMarket(CourseMarket courseMarket){
        // TODO 验证信息合法性
        if (!StringUtils.isNotEmpty(courseMarket.getCharge())){
            xuechengplusException.cast("请设置收费规则");
        }

        if (courseMarket.getCharge().equals("201001")){
            if (courseMarket.getOriginalPrice()<=0 || courseMarket.getOriginalPrice()==null ||
                    courseMarket.getPrice()<=0 ||courseMarket.getPrice()==null){
                xuechengplusException.cast("课程价格设置不能为空或小于0");
            }
        }

        //查询数据库中是否存在该信息
        CourseMarket isCourseMarket = courseMarketMapper.selectById(courseMarket.getId());
        if (isCourseMarket==null){
            //不存在插入
            int insert = courseMarketMapper.insert(courseMarket);
            return insert;
        }
        //存在，进行修改
        int success = courseMarketMapper.updateById(courseMarket);
        return success;
    }
}
